#!/bin/sh
set -e

add_groups()
{
    if ! getent passwd iotedge >/dev/null; then
        adduser --system iotedge --home /var/lib/iotedge --shell /bin/false
    fi

    if ! getent group iotedge >/dev/null; then
        addgroup --system iotedge
    fi

    # add iotedge user to docker group so that it can talk to the docker socket
    if getent group docker >/dev/null; then
        adduser iotedge docker
    fi

    # Add each admin user to the iotedge group - for systems installed before precise
    for u in $(getent group admin | sed -e "s/^.*://" -e "s/,/ /g"); do
        adduser "$u" iotedge >/dev/null || true
    done

    # Add each sudo user to the iotedge group
    for u in $(getent group sudo | sed -e "s/^.*://" -e "s/,/ /g"); do
        adduser "$u" iotedge >/dev/null || true
    done
}

check_runtime()
{
    # Verify a container runtime exists before installing.

    if ! getent group docker >/dev/null; then
        echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        echo ""
        echo " ERROR: No container runtime detected."
        echo ""
        echo " Please install a container runtime and run this install again."
        echo ""
        echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

        exit 1
    fi
}

case "$1" in
    install|upgrade)
        check_runtime
        add_groups
    ;;

    abort-upgrade)
    ;;

    *)
        echo "preinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac


#DEBHELPER#

exit 0
